<script setup lang="ts">
import type { BasicRadioGroupProps } from '@/components/form/src/components/radio-group/props';
import { usePageDataStore } from '@/store/modules/page-data';

const props = withDefaults(defineProps<BasicRadioGroupProps>(), {
  disabled: false,
  defaultValue: null,
  defaultFirst: false,
  labelField: 'label',
  valueField: 'value',
});
const emits = defineEmits<{
  (e: 'update:value', value: string | number | boolean | null | undefined): void;
}>();

const localValue = ref();
const options = ref(props.options);

watchImmediate(() => props.value, value => {
  localValue.value = value;
});

/**
 * 获取共享数据
 *
 * 注意：监听会执行两次 第二次在表单项v-modal中
 */
watchImmediate(() => props.shareDataKey, key => {
  if (key) {
    options.value = usePageDataStore().get<Option[]>(key) ?? [];
    if (props.defaultFirst) {
      localValue.value = options.value[0]?.[props.valueField] as any;
    }
  }
});

function handleUpdateValue(value: string | number | boolean) {
  emits('update:value', value);
}
</script>

<template>
  <NRadioGroup
    :value="localValue"
    :default-value="props.defaultValue"
    name="radiogroup"
    @update:value="handleUpdateValue"
  >
    <NSpace>
      <NRadio v-for="option of options" :key="option.value" :value="option.value">
        {{ option.label }}
      </NRadio>
    </NSpace>
  </NRadioGroup>
</template>

<style scoped lang="less">

</style>
